package cn.edu.ncut.cs.springboot.springsecuritydemo.service.impl;

import cn.edu.ncut.cs.springboot.springsecuritydemo.entity.Book;
import cn.edu.ncut.cs.springboot.springsecuritydemo.entity.User;
import cn.edu.ncut.cs.springboot.springsecuritydemo.repository.BookRepository;
import cn.edu.ncut.cs.springboot.springsecuritydemo.service.BookService;
import cn.edu.ncut.cs.springboot.springsecuritydemo.vo.BookVO;
import cn.edu.ncut.cs.springboot.springsecuritydemo.vo.UserVO;
import jakarta.persistence.Cacheable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * ClassName : BookServiceImpl
 * package : cn.edu.ncut.cs.springboot.springsecuritydemo.service.impl
 * Description :
 *
 * @ Author Dreama
 * @ Creat 2024/12/24 15:54
 * @ Version 1.0
 */
@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookRepository bookRepository;

    @Override
    public List<BookVO> findAll(){
//        clearCache();
        return bookRepository.findAll().stream().map(book -> {
            BookVO bookVO = new BookVO();
            bookVO.setId(book.getid());
            bookVO.setTitle(book.getTitle());
            return bookVO;
        }).collect(Collectors.toList());
    }

    @Override
//    @Cacheable("booksByTitle")
    public Optional<Book> getByTitle(@NonNull String title) {
        List<Book> result = bookRepository.getBookByTitle(title);
        return Optional.ofNullable(result.isEmpty() ? null : result.get(0));
    }

    @Override
    public boolean create(BookVO bookVO) {
        String title = bookVO.getTitle();
        String author = bookVO.getAuthor();
        String isbn = bookVO.getIsbn();
        /*由于使用了BCryptPasswordEncoder实现（在SecurityConfig中已经给出相关的bean定义），无需用盐*/
        // String salt = null;
        Instant now = Instant.now();
        Book book = Book.builder()
                .title(title)
                .author(author)
                .isbn(isbn)
                .build();
        /*记录操作时间*/
        bookVO.setTimestamp(now.toEpochMilli());
        try {
            book = bookRepository.save(book);
            bookVO.setId(book.getid());
            return true;
        } catch (Exception e) {
            System.err.println("注册用户出错！");
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Book getById(Long id) {
        return bookRepository.getOne(id);
    }
//    @CacheEvict(value = "booksByTitle", allEntries = true)
//    public void clearCache() {
//        // 这个方法不执行任何操作，只用来清除缓存
//    }
    @Override
    public Book saveBook(Book book){
        return bookRepository.save(book);
    }

}
